﻿using System;
using System.Collections.Generic;

namespace Core.Base.Model
{
    /// <summary>
    /// Model管理类的基类
    /// </summary>
    public abstract class BaseModelMgr : BaseMgr
    {
        private Dictionary<Type, BaseModel> cacheModels = new Dictionary<Type, BaseModel>();

        public override void OnInit()
        {
            base.OnInit();
            RegModels();
        }

        public abstract void RegModels();

        public T RegModel<T>() where T : BaseModel
        {
            Type type = typeof(T);
            T model = default;
            if (!cacheModels.ContainsKey(type))
            {
                model = Activator.CreateInstance<T>();
                model.OnInit();
                cacheModels.Add(type, model);
            }

            return model;
        }

        public void UnRegModel<T>() where T : BaseModel
        {
            Type type = typeof(T);
            if (cacheModels.TryGetValue(type, out var model))
            {
                model.OnDestroy();
                cacheModels.Remove(type);
            }
        }

        public T RetrieveModel<T>() where T : BaseModel
        {
            Type type = typeof(T);
            BaseModel model = default;
            cacheModels.TryGetValue(type, out model);
            return model as T;
        }

        public override void OnDestroy()
        {
            foreach (var item in cacheModels.Values)
            {
                item.OnDestroy();
            }

            cacheModels.Clear();
            base.OnDestroy();
        }

      

        public virtual void OnClear()
        {
            foreach (var item in cacheModels.Values)
            {
                item.OnClear();
            }
        }
    }
}